<template>
    <view class="order-purchase">
        <view class="content">
            <!-- 地址选择区域 -->
            <view class="address-section" @click="selectAddress">
                <view class="address-info">
                    <text class="address-text">
                        {{ addressInfo && addressInfo.id ? (addressInfo.name + ', ' + (addressInfo.phone || '') + ', ' + (addressInfo.address || '')) : '请选择地址' }}
                    </text>
                </view>
                <view class="address-arrow">
                    <uni-icons type="right" size="16" color="#999"></uni-icons>
                </view>
            </view>

            <!-- 商品详情区域 -->
            <!-- 从购物车进入：显示多个商品 -->
            <view v-if="fromCart && shoppingList.length > 0">
                <view class="product-section" v-for="(item, index) in shoppingList" :key="index">
                    <image :src="item.img" mode="aspectFill" class="product-image"></image>
                    <view class="product-info">
                        <view class="product-title">{{ item.title || item.name }}</view>
                        <view class="product-spec" v-if="item.norm || item.spec">{{ item.norm || item.spec }}</view>
                        <view class="price-quantity-row">
                            <view class="product-price">¥{{ item.price }}</view>
                            <view class="quantity-selector">
                                <view class="quantity-btn" :class="{ 'disabled': item.num <= 1 }" @click="decreaseCartQuantity(index)">
                                    <uni-icons type="minus" size="25" color="#333"></uni-icons>
                                </view>
                                <view class="quantity-value">{{ item.num }}</view>
                                <view class="quantity-btn" :class="{ 'disabled': item.num >= maxQuantity }"
                                    @click="increaseCartQuantity(index)">
                                    <uni-icons type="plus" size="25" color="#333"></uni-icons>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <!-- 从商品详情进入：显示单个商品 -->
            <view class="product-section" v-else-if="orderInfo">
                <image :src="orderInfo.productImg" mode="aspectFill" class="product-image"></image>
                <view class="product-info">
                    <view class="product-title">{{ orderInfo.productTitle }}</view>
                    <view class="product-spec" v-if="orderInfo.spec">{{ orderInfo.spec }}</view>
                    <view class="price-quantity-row">
                        <view class="product-price">¥{{ orderInfo.price }}</view>
                        <view class="quantity-selector">
                            <view class="quantity-btn" :class="{ 'disabled': quantity <= 1 }" @click="decreaseQuantity">
                                <uni-icons type="minus" size="25" color="#333"></uni-icons>
                            </view>
                            <view class="quantity-value">{{ quantity }}</view>
                            <view class="quantity-btn" :class="{ 'disabled': quantity >= maxQuantity }"
                                @click="increaseQuantity">
                                <uni-icons type="plus" size="25" color="#333"></uni-icons>
                            </view>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 价格明细区域 -->
            <view class="price-section">
                <view class="price-item">
                    <text class="price-label">商品金额:</text>
                    <text class="price-value">¥{{ productAmount }}</text>
                </view>
                <view class="price-item">
                    <text class="price-label">运费:</text>
                    <text class="price-value">¥{{ shippingFee }}</text>
                </view>
                <view class="price-item">
                    <text class="price-label">优惠券抵扣:</text>
                    <text class="price-value">¥{{ couponDiscount }}</text>
                </view>
                <view class="price-divider"></view>
                <view class="price-item total">
                    <text class="price-label">总价:</text>
                    <text class="price-value total-price">¥{{ totalPrice }}</text>
                </view>
            </view>
        </view>

        <!-- 底部固定栏 -->
        <view class="bottom-bar">
            <view class="bottom-total">
                <text class="total-label">总价: </text>
                <text class="total-value">¥{{ totalPrice }}</text>
            </view>
            <view class="btn-pay" @click="handlePay">立即购买</view>
        </view>
    </view>
</template>

<script>
import { orderApi, shoppingApi, addressApi, productApi } from '@/api/indexAPI.js';
import { public_img } from '@/static/public.js';

export default {
    data() {
        return {
            statusBarHeight: 0, // 状态栏高度
            addressSelectedManually: false, // 是否在地址列表中手动选择了地址（用于返回后是否刷新默认地址）
            orderInfo: null, // 订单信息（从商品详情进入）
            quantity: 1, // 数量
            maxQuantity: 999, // 最大数量
            fromCart: false, // 是否从购物车进入
            shoppingList: [], // 购物车商品列表
            shoppingIds: [], // 购物车商品ID数组（用于支付）
            totalPriceFromCart: 0, // 从购物车传入的总价
            addressInfo: {
                id: '', // 地址ID，默认值，后续可从接口获取
                name: '',
                phone: '',
                address: ''
            },
            shippingFee: '0', // 运费
            couponDiscount: '0' // 优惠券抵扣
        };
    },
    onShow() {
        // 返回本页时，若未手动选择地址，则根据默认地址刷新一次
        if (!this.addressSelectedManually) {
            this.loadDefaultAddress();
        } else {
            // 已经手动选择过地址，本次返回不再覆盖
            this.addressSelectedManually = false;
        }
    },
    computed: {
        // 计算商品金额
        productAmount() {
            // 从购物车进入：计算所有商品的总价
            if (this.fromCart && this.shoppingList.length > 0) {
                const total = this.shoppingList.reduce((sum, item) => {
                    const price = parseFloat(item.price || 0);
                    const num = item.num || item.quantity || 1;
                    return sum + (price * num);
                }, 0);
                return total.toFixed(2);
            }
            // 从商品详情进入：计算单个商品价格
            if (!this.orderInfo) return '0.00';
            const price = parseFloat(this.orderInfo.price || 0);
            const qty = this.quantity || 1;
            return (price * qty).toFixed(2);
        },
        // 计算总价
        totalPrice() {
            // 从购物车进入：实时计算总价
            if (this.fromCart && this.shoppingList.length > 0) {
                const productAmt = parseFloat(this.productAmount || 0);
                const shipping = parseFloat(this.shippingFee || 0);
                const coupon = parseFloat(this.couponDiscount || 0);
                const total = productAmt + shipping - coupon;
                return total > 0 ? total.toFixed(2) : '0.00';
            }
            // 从商品详情进入：计算单个商品总价
            if (!this.orderInfo) return '0.00';
            const productAmt = parseFloat(this.productAmount || 0);
            const shipping = parseFloat(this.shippingFee || 0);
            const coupon = parseFloat(this.couponDiscount || 0);
            const total = productAmt + shipping - coupon;
            return total > 0 ? total.toFixed(2) : '0.00';
        }
    },
    async onLoad(options) {
        // 获取设备状态栏高度
        this.getStatusBarHeight();

        // 判断是否从购物车进入
        if (options.from === 'cart' && options.shoppingIds) {
            try {
                this.fromCart = true;
                // 解析购物车商品ID数组（用于支付接口）
                this.shoppingIds = JSON.parse(decodeURIComponent(options.shoppingIds));
                this.totalPriceFromCart = parseFloat(options.totalPrice || 0);
                
                // 解析购物车商品列表（用于显示）
                if (options.shoppingList) {
                    this.shoppingList = JSON.parse(decodeURIComponent(options.shoppingList));
                    // 处理图片路径
                    this.shoppingList = this.shoppingList.map(item => ({
                        ...item,
                        img: item.img && item.img.startsWith('http') 
                            ? item.img 
                            : (public_img + (item.img || ''))
                    }));
                } else {
                    // 如果没有传递完整商品信息，使用shoppingIds构建基本列表
                    // 注意：shoppingIds中的money是单价
                    this.shoppingList = this.shoppingIds.map(item => ({
                        id: item.id,
                        goods_id: item.goods_id,
                        num: item.num,
                        price: parseFloat(item.money || 0), // money是单价，直接作为price
                        money: parseFloat(item.money || 0) * item.num, // 总价用于显示
                        title: '',
                        img: '',
                        norm: '',
                        spec: ''
                    }));
                }
                
                console.log('购物车商品列表:', this.shoppingList);
                console.log('购物车商品ID数组:', this.shoppingIds);
                // 获取购物车每个商品的库存进行合并
                await this.fetchStocksForCart();
            } catch (error) {
                console.error('解析购物车商品信息失败:', error);
                uni.showToast({
                    title: '商品信息错误',
                    icon: 'none'
                });
                setTimeout(() => {
                    uni.navigateBack();
                }, 1500);
            }
        } else if (options.orderInfo) {
            // 从商品详情进入
            try {
                this.orderInfo = JSON.parse(decodeURIComponent(options.orderInfo));
                this.quantity = this.orderInfo.quantity || 1;
                console.log('订单信息:', this.orderInfo);
                // 从商品详情支付：根据 productId 获取库存
                if (this.orderInfo && this.orderInfo.productId) {
                    await this.fetchStockForOrder(this.orderInfo.productId);
                }
            } catch (error) {
                console.error('解析订单信息失败:', error);
                uni.showToast({
                    title: '订单信息错误',
                    icon: 'none'
                });
                setTimeout(() => {
                    uni.navigateBack();
                }, 1500);
            }
        } else {
            uni.showToast({
                title: '缺少订单信息',
                icon: 'none'
            });
            setTimeout(() => {
                uni.navigateBack();
            }, 1500);
        }

        // 加载默认地址（default 为 1）
        this.loadDefaultAddress();
    },
    methods: {
        // 获取设备状态栏高度
        getStatusBarHeight() {
            try {
                const systemInfo = uni.getSystemInfoSync();
                this.statusBarHeight = systemInfo.statusBarHeight || 0;
            } catch (err) {
                console.error('获取状态栏高度失败', err);
                this.statusBarHeight = 20;
            }
        },
        // 获取单个商品库存（用于从商品详情进入的支付）
        async fetchStockForOrder(productId) {
            try {
                const res = await productApi.getProductDetail(productId);
                const stock = res?.data?.stock;
                if (typeof stock !== 'undefined') {
                    this.maxQuantity = Number(stock) > 0 ? Number(stock) : 0;
                    if (this.quantity > this.maxQuantity) this.quantity = this.maxQuantity;
                }
            } catch (e) {
                console.error('获取单品库存失败', e);
            }
        },
        // 批量获取购物车商品库存（根据 goods_id）
        async fetchStocksForCart() {
            try {
                const tasks = (this.shoppingList || []).map(async (it) => {
                    const goodsId = it.goods_id;
                    if (!goodsId) return;
                    try {
                        const res = await productApi.getProductDetail(goodsId);
                        const stock = res?.data?.stock;
                        if (typeof stock !== 'undefined') {
                            it.stock = Number(stock);
                            if (it.num > it.stock) it.num = it.stock;
                        }
                    } catch (err) {
                        console.error('获取购物车商品库存失败', goodsId, err);
                    }
                });
                await Promise.all(tasks);
            } catch (e) {
                console.error('批量获取库存失败', e);
            }
        },

        // 加载默认地址：优先 default/dufault === '1'，没有则取第一条
        async loadDefaultAddress() {
            try {
                const res = await addressApi.getAddressList();
                if (res && res.code === 1 && Array.isArray(res.data)) {
                    const list = res.data;
                    // 兼容 number/string
                    const def = list.find(a => String(a.default ?? a.dufault) === '1');
                    const picked = def || list[0];
                    if (picked) {
                        this.addressInfo = {
                            id: picked.id,
                            name: picked.name,
                            phone: picked.tel || picked.phone,
                            address: `${picked.address || ''}${picked.desc || ''}`
                        };
                    } else {
                        // 没有地址则清空（由模板显示“请选择地址”）
                        this.addressInfo = { id: '', name: '', phone: '', address: '' };
                    }
                }
            } catch (e) {
                console.error('加载默认地址失败', e);
            }
        },
        // 选择地址
        selectAddress() {
            uni.navigateTo({
                url: '/pages/location/index',
                events: {
                    // 接收地址列表页回传的地址
                    addressSelected: (addr) => {
                        if (addr && addr.id) {
                            this.addressSelectedManually = true;
                            this.addressInfo = {
                                id: addr.id,
                                name: addr.name,
                                phone: addr.tel || addr.phone,
                                address: `${addr.address || ''}${addr.desc || ''}`
                            };
                        }
                    }
                }
            });
        },

        // 减少数量
        decreaseQuantity() {
            if (this.quantity > 1) {
                this.quantity--;
                // 更新订单信息中的数量
                if (this.orderInfo) {
                    this.orderInfo.quantity = this.quantity;
                }
            }
        },

        // 增加数量
        increaseQuantity() {
            // 有库存上限时进行拦截
            if (typeof this.maxQuantity === 'number' && this.maxQuantity >= 0 && this.quantity >= this.maxQuantity) {
                uni.showToast({ title: '库存不足', icon: 'none' });
                return;
            }
            if (this.quantity < this.maxQuantity) {
                this.quantity++;
                // 更新订单信息中的数量
                if (this.orderInfo) {
                    this.orderInfo.quantity = this.quantity;
                }
            } else {
                uni.showToast({
                    title: '已达到最大数量',
                    icon: 'none'
                });
            }
        },

        // 减少购物车商品数量
        decreaseCartQuantity(index) {
            if (this.shoppingList[index] && this.shoppingList[index].num > 1) {
                this.shoppingList[index].num--;
                this.updateCartItemQuantity(index);
            }
        },

        // 增加购物车商品数量
        increaseCartQuantity(index) {
            if (this.shoppingList[index] && this.shoppingList[index].num < this.maxQuantity) {
                // 若条目含库存字段，则按库存限制
                const item = this.shoppingList[index];
                if (typeof item.stock === 'number' && item.stock >= 0 && item.num >= item.stock) {
                    uni.showToast({ title: '库存不足', icon: 'none' });
                    return;
                }
                this.shoppingList[index].num++;
                this.updateCartItemQuantity(index);
            } else {
                uni.showToast({
                    title: '已达到最大数量',
                    icon: 'none'
                });
            }
        },

        // 更新购物车商品数量并重新计算总价
        updateCartItemQuantity(index) {
            const item = this.shoppingList[index];
            if (!item) return;

            // 更新shoppingList中的金额（用于显示，这里是总价）
            item.money = parseFloat(item.price) * item.num;

            // 更新shoppingIds中对应商品的数量
            // 注意：shoppingIds中的money应该是单价，不是总价
            const shoppingIdItem = this.shoppingIds.find(sid => sid.id === item.id || sid.goods_id === item.goods_id);
            if (shoppingIdItem) {
                shoppingIdItem.num = item.num;
                // money保持为单价，不改变
                if (!shoppingIdItem.money || shoppingIdItem.money !== parseFloat(item.price)) {
                    shoppingIdItem.money = parseFloat(item.price);
                }
            }

            // 重新计算总价
            this.totalPriceFromCart = this.shoppingList.reduce((sum, cartItem) => {
                return sum + (parseFloat(cartItem.price || 0) * (cartItem.num || 1));
            }, 0);
        },

        // 处理支付
        async handlePay() {
            // 验证地址ID
            if (!this.addressInfo.id) {
                uni.showToast({
                    title: '请选择收货地址',
                    icon: 'none'
                });
                return;
            }

            // 显示加载提示
            uni.showLoading({
                title: '支付中...',
                mask: true
            });

            try {
                let response;
                
                if (this.fromCart && this.shoppingIds.length > 0) {
                    // 从购物车支付：调用购物车支付接口
                    response = await shoppingApi.payFromCart(
                        this.shoppingIds,
                        this.addressInfo.id
                    );
                } else if (this.orderInfo) {
                    // 从商品详情支付：调用订单支付接口
                    // 构建规格参数
                    let norm = '';
                    if (this.orderInfo.spec && this.orderInfo.specName) {
                        norm = JSON.stringify([{
                            name: 'name',
                            value: this.orderInfo.spec
                        }]);
                    } else {
                        norm = JSON.stringify([{
                            name: 'name',
                            value: this.orderInfo.productTitle || ''
                        }]);
                    }
                    
                    response = await orderApi.payOrder(
                        this.addressInfo.id, // address_id
                        this.orderInfo.productId, // goods_id
                        this.quantity, // num
                        norm, // norm
                        this.totalPrice // money
                    );
                } else {
                    throw {
                        code: -1,
                        msg: '订单信息错误'
                    };
                }

                // 隐藏加载提示
                uni.hideLoading();

                // 检查返回结果
                if (response && response.code === 1) {
                    // 支付成功，跳转到订单页面
                    uni.showToast({
                        title: '支付成功',
                        icon: 'success',
                        duration: 1500
                    });

                    // 延迟跳转，让用户看到成功提示
                    setTimeout(() => {
                        uni.redirectTo({
                            url: '/pages/order/index'
                        });
                    }, 1500);
                } else {
                    // 支付失败
                    throw {
                        code: response.code || -10,
                        msg: response.msg || '支付失败'
                    };
                }
            } catch (error) {
                // 隐藏加载提示
                uni.hideLoading();

                console.error('支付失败:', error);

                // 显示错误提示
                let errorMsg = '支付失败，请稍后重试';
                if (error.msg) {
                    errorMsg = error.msg;
                } else if (error.data && error.data.msg) {
                    errorMsg = error.data.msg;
                }

                uni.showToast({
                    title: errorMsg,
                    icon: 'none',
                    duration: 2000
                });
            }
        }
    }
};
</script>

<style lang="scss" scoped>
.order-purchase {
    min-height: 100vh;
    background-color: #ffffff;
    padding-bottom: 100rpx;
}

/* 地址选择区域 */
.address-section {
    padding: 30rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20rpx;
    border-bottom: 1px solid #999999;
}

.address-info {
    flex: 1;
}

.address-text {
    font-size: 15px;
    color: #717171;
    line-height: 1.5;
}

.address-arrow {
    margin-left: 20rpx;
}

/* 商品详情区域 */
.product-section {
    padding: 30rpx;
    display: flex;
    align-items: flex-start;
    margin-bottom: 20rpx;
    border-bottom: 1px solid #999999;
}

.product-section:last-child {
    border-bottom: none;
}

.product-image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 16rpx;
    margin-right: 20rpx;
    flex-shrink: 0;
}

.product-info {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.product-title {
    font-size: 17px;
    color: #717171;
    margin-bottom: 10rpx;
    line-height: 1.4;
}

.product-spec {
    font-size: 14px;
    color: #999;
    margin-bottom: 10rpx;
}

.price-quantity-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.product-price {
    font-size: 17px;
    color: #ff0000;
}

.quantity-selector {
    display: flex;
    align-items: center;
}

.quantity-btn {
    width: 23px;
    height: 23px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    color: #333;
}

.quantity-btn.disabled {
    border-color: #eee;
}

.quantity-btn.disabled .uni-icons {
    color: #ccc !important;
}

.quantity-value {
    margin: 0 20rpx;
    font-size: 28rpx;
    color: #333;
    min-width: 40rpx;
    text-align: center;
}


/* 价格明细区域 */
.price-section {
    padding: 30rpx;
}

.price-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20rpx;
}

.price-item:last-child {
    margin-bottom: 0;
}

.price-item.total {
    margin-top: 20rpx;
    display: flex;
    justify-content: flex-end;
    gap: 5px;
}

.price-label {
    font-size: 28rpx;
    color: #949494;
}

.price-value {
    font-size: 28rpx;
    color: #949494;
}

.price-divider {
    height: 0.5px;
    background-color: #999999;
    margin: 20rpx 0;
}

/* 底部固定栏 */
.bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 100rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 30rpx;
    z-index: 999;
}

.bottom-total {
    display: flex;
    align-items: center;
}

.total-label {
    font-size: 14px;
    color: #9b9b9b;
    margin-right: 5px;
}

.total-value {
    font-size: 14px;
    color: #9b9b9b;
}

.btn-pay {
    width: 117px;
    height: 36px;
    background-color: #ff0000;
    border-radius: 35rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    color: #fff;
    font-weight: 700;
}
</style>
